package deng.hibernate.examples.employees.cli;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public abstract class AbstractEntityManagerExample {
	
	public static void println(Object object) {
		System.out.println(object.toString());
	}
	
	private String persistenceUnitName;
	
	public void setPersistenceUnitName(String persistenceUnitName) {
		this.persistenceUnitName = persistenceUnitName;
	}
	
	protected void run() {
		println("Creating EntityManager with persistenceUnitName=" + persistenceUnitName);
		EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
		EntityManager em = emf.createEntityManager();
		runExample(em);
		
		println("Closing EntityManager.");
		em.close();
		emf.close();
	}

	protected void runExample(EntityManager em) {
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			println("Transaction started.");
			runTxExample(em);
			tx.commit();
			println("Transaction commited.");
		} catch (Exception e) {
			if (tx.isActive()) {
				tx.rollback();
				println("Transaction rollback completed.");
			}
			throw new RuntimeException(e);
		}
		
	}

	protected abstract void runTxExample(EntityManager em);
	
}
